package huixue.cn.com.rxapp.util;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wang.avi.AVLoadingIndicatorView;

import huixue.cn.com.rxapp.R;

/**
 * Created by gongdongyang on 2018/7/17.
 */

public class UIHelper {

    private static Dialog mLoadingDialog;

    /**
     * 显示加载对话框
     *
     * @param context 上下文
     * @param msg     对话框显示内容
     */
    public static void showDialogForLoading(Context context, String msg) {
        View view = LayoutInflater.from(context).inflate(R.layout.loading, null);
        TextView loadingText = view.findViewById(R.id.id_tv_loading_dialog_text);
        AVLoadingIndicatorView avLoadingIndicatorView = view.findViewById(R.id.AVLoadingIndicatorView);
        loadingText.setText(msg);
//        if (mLoadingDialog == null)
        mLoadingDialog = new Dialog(context, R.style.MyDialog);
        mLoadingDialog.setCancelable(false);
        mLoadingDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        WindowManager.LayoutParams params = mLoadingDialog.getWindow().getAttributes();
        // 设置宽高为match_parent，不要去算出来屏幕宽高再赋值哦，因为有些
        // 有虚拟按键的手机上计算出来的高度不一定准确，所以dialog不会全屏
                params.width = WindowManager.LayoutParams.MATCH_PARENT;
                params.height = WindowManager.LayoutParams.MATCH_PARENT;
        //mLoadingDialog.getWindow().setAttributes(params);
        mLoadingDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        mLoadingDialog.show();
        avLoadingIndicatorView.smoothToShow();
        mLoadingDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    mLoadingDialog.hide();
                    return true;
                }
                return false;
            }
        });
    }

    public static void destroyDialogForLoading() {
        if (mLoadingDialog != null) {
//            mLoadingDialog.hide();
            mLoadingDialog.dismiss();
        }
    }
}
